<?php
namespace app\pay\controller;
use think\Input;
class Paydemo extends Common{
    public function initialize(){
        parent::initialize();  
    }  
    // 收银台或统一订单
    public function index($site='',$gotopay='',$money='',$paytype='',$note=''){ 
        $channelid=$site?$site:0;
        if($channelid){
            $channeinfo=db('channel')->where(array('id' =>$channelid , 'open' =>1 , 'state' =>0 , ))->find();
            if($channeinfo){  
                $newdata = array(
                    "orderid_out" => date("YmdHis",time()), //商户订单号 string
                    "appid" => $channeinfo['shopappid'], //商户APPID 固定派发 string
                    "shopid" => $channeinfo['shopid'], //商户ID 固定派发 int
                    "channelid" => $channeinfo['id'], //通道ID 动态派发 int
                    "paytype" => $paytype, //支付ID 动态派发  string
                    "money" => $money, //订单金额 string
                    "returnurl" => '', //跳转链接 string
                    "notifyurl" => '', //通知链接 string http://localhost:5691/pay/notifydemo/index
                    "version" => $this->sys['version'], //签名版本号 固定派发 string             
                );   

                ksort($newdata); //按照键名进行升序排序                
                $Md5key=db('shop')->where('id',$channeinfo['shopid'])->value('appkey');
                $md5str = "";
                foreach ($newdata as $key => $val) {
                    if (!empty($val)) {
                        $md5str = $md5str . $key . "=" . $val . "&";
                    }
                }  
                $sign = strtoupper(md5($md5str . "key=" . $Md5key));  //签名转大写
                $newdata["sign"] = $sign;
                $newdata['note']=$note; //备注 
                $gotopay=$gotopay; //提交地址 动态派发
                // var_dump($gotopay);die;
                //db('table')->insert($newdata);
                // 商户写入数据成功后,提交数据
                
                $curl = curl_init();
                curl_setopt($curl, CURLOPT_URL,$gotopay);//设置抓取的url
                curl_setopt($curl, CURLOPT_HEADER, 'Content-Type:application/x-www-form-urlencoded');//设置头文件的信息作为数据流输出
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//设置获取的信息以文件流的形式返回，而不是直接输出。
                curl_setopt($curl, CURLOPT_POST, 1);//设置post方式提交
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
                curl_setopt($curl, CURLOPT_POSTFIELDS, $md5str."&sign=".$newdata['sign']."&note=".$newdata['note']);
                curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
                $res_data = curl_exec($curl);//执行命令
                curl_close($curl);//关闭URL请求
                $res=json_decode($res_data,true);
                if(isset($res['returnurl'])){
                    header("Location:".$res['returnurl']);
                }else{
                    echo $res_data;
                }  
            }
        }
        
    } 
}  